<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item size="mini">
        <el-input v-model="courseQueryObj.courseCode" placeholder="课程代码" @change="getCourseList(0)"/>
      </el-form-item>
      <el-form-item size="mini">
        <el-input v-model="courseQueryObj.courseName" placeholder="课程名称" @change="getCourseList(0)"/>
      </el-form-item>
      <el-form-item size="mini">
        <el-input v-model="courseQueryObj.nextCourseStr" placeholder="后继课程名称" @change="getCourseList(0)"/>
      </el-form-item>
      <el-form-item size="mini">
        <el-input v-model="courseQueryObj.propertiesKey" placeholder="属性键" @change="getCourseList(0)"/>
      </el-form-item>
      <el-form-item size="mini">
        <el-input v-model="courseQueryObj.propertiesValue" placeholder="属性值" @change="getCourseList(0)"/>
      </el-form-item>
      <el-form-item size="mini">
        <el-input v-model="courseQueryObj.createdByName" placeholder="创建人姓名" @change="getCourseList(0)"/>
      </el-form-item>
      <!--      <el-form-item label="开始时间" size="mini">-->
      <!--        <el-date-picker-->
      <!--          v-model="courseQueryObj.beginTime"-->
      <!--          type="datetime"-->
      <!--          placeholder="选择开始时间"-->
      <!--          value-format="yyyy-MM-dd HH:mm:ss"-->
      <!--          default-time="00:00:00"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="结束时间" size="mini">-->
      <!--        <el-date-picker-->
      <!--          v-model="courseQueryObj.updateTime"-->
      <!--          type="datetime"-->
      <!--          placeholder="选择截止时间"-->
      <!--          value-format="yyyy-MM-dd HH:mm:ss"-->
      <!--          default-time="00:00:00"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-button type="primary" icon="el-icon-search" @click="getCourseList()" size="mini">搜索</el-button>
      <el-button type="default" icon="el-icon-refresh" @click="resetData()" size="mini">重置</el-button>
    </el-form>

    <!-- 新增、导入、导出按钮   -->
    <div class="buttonClass">
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="addCourse"
      >新增
      </el-button>

      <el-upload action="handleImport"
                 :http-request="handleImport"
                 :headers="headers"
                 :before-upload="beforeUpload"
                 :on-success="onSuccess"
                 :on-error="onError"
                 :show-file-list="false"
                 :disabled="importDataDisabled"
                 style="display: inline-flex;margin: 8px">
        <el-button
          type="success" plain size="mini"
          :disabled="importDataDisabled"
          :icon="importDataBtnIcon"
        >
          {{ importDataBtnText }}
        </el-button>
      </el-upload>

      <el-tooltip class="item" effect="dark" content="导出选中数据，若未选中任何数据则导出所有数据" placement="right-start">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出数据
        </el-button>
      </el-tooltip>

    </div>

    <!-- 课程列表 -->
    <el-table
      :data="courseList"
      row-key="courseId"
      ref="courseTable"
      @selection-change="handleSelectionChange"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      style="width: 100%;margin-bottom: 20px;"
      border fit highlight-current-row>
      <el-table-column type="selection" width="55"/>

      <el-table-column prop="courseCode" label="课程代码" width="130"/>

      <el-table-column prop="courseName" label="课程名称" show-overflow-tooltip/>

      <el-table-column prop="nextCourseStr" label="后继课程" show-overflow-tooltip/>

      <el-table-column prop="propertiesKey" label="属性键"/>

      <el-table-column prop="propertiesValue" label="属性值"/>

      <!--      <el-table-column prop="createdByName" label="创建人"/>-->

      <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip/>

      <el-table-column prop="updateTime" label="修改时间" show-overflow-tooltip/>

      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <!--修改课程信息-->
          <el-tooltip class="item" effect="dark" content="修改课程信息" placement="top-start">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="openCourseDialogForm(scope.row)">
            </el-button>
          </el-tooltip>
          <!--修改后继课程信息-->
          <el-tooltip class="item" effect="dark" content="修改关联课程信息" placement="top-start">
            <el-button type="info" size="mini" icon="el-icon-more" @click="openNextCourseDialogForm(scope.row)">
            </el-button>
          </el-tooltip>
          <!--删除课程信息-->
          <el-tooltip class="item" effect="dark" content="删除课程信息" placement="top-start">
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteCourseById(scope.row.courseId)">
            </el-button>
          </el-tooltip>
          <!-- 查看目录-->
          <el-tooltip class="item" effect="dark" content="查看目录信息" placement="top-start">
            <el-button type="warning" size="mini" @click="gotoCategory(scope.row.courseId)">
              <i class="el-icon-arrow-right el-icon--right"></i>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      background
      layout="prev, pager, next"
      style="padding: 30px 0; text-align: center;"
      @current-change="getCourseList"
    />

    <!-- 修改或增加课程信息弹出框 -->
    <el-dialog title="修改课程信息" :visible.sync="courseDialogFormVisible">
      <el-form :model="courseInfo" ref="newCourseInfoForm">
        <el-form-item
          label="课程名称"
          prop="courseName"
          label-width="100px">
          <el-input v-model="courseInfo.courseName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="属性键" label-width="100px">
          <el-input v-model="courseInfo.propertiesKey" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="属性值" label-width="100px">
          <el-input v-model="courseInfo.propertiesValue" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearCourseInfo">取 消</el-button>
        <el-button type="primary" @click="updateOrCourseInfo()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改后继课程信息 -->
    <el-dialog title="修改关联课程信息" :visible.sync="nextCourseDialogFormVisible">
      <el-form>
        <el-form-item label="课程名称" label-width="100px">
          <el-input
            v-model="currentCourse.courseName"
            :disabled="true">
          </el-input>
        </el-form-item>

        <el-form-item label="可选后继课程">
          <el-select v-model="nextCoursesIdAndName" clearable value-key="courseId" filterable placeholder="请选择后继课程名称">
            <el-option
              v-for="coursesIdAndName in canBeAddedNextCourseList"
              :key="coursesIdAndName.courseId"
              :label="coursesIdAndName.courseName"
              :value="coursesIdAndName">
            </el-option>
          </el-select>

          <el-select v-model="nextCoursesIdAndName.relationLevel" placeholder="请选择关联等级">
            <el-option
              v-for="item in relationLevelList"
              :key="item.relationLevel"
              :label="item.relationName"
              :value="item.relationLevel"/>
          </el-select>
          <el-tooltip class="item" effect="dark" content="1为弱关联、2为半关联、3为强关联、4为全关联" placement="top-end">
            <el-button class="noBorder"
                       icon="el-icon-circle-plus-outline"
                       @click="addNextCourse(currentCourse.courseId, nextCoursesIdAndName)"/>
          </el-tooltip>
        </el-form-item>

        <!--动态编辑后继课程标签-->
        <el-form-item label="后继课程列表">
          <el-tag
            v-for="nextCourse in nextCourseList"
            :key="nextCourse.courseId"
            closable
            :type="colorObj[nextCourse.relationLevel]"
            @close="handleNextCourseTagClose(nextCourse)">
            {{ nextCourse.courseName }}
          </el-tag>
        </el-form-item>

        <!-- 色块说明 -->
        <el-form-item label="颜色含义" label-width="100px">
          <div style=" display: inline-block; background: #909399;width: 10px; height: 10px; margin: 0 auto"/>
          <div style="display: inline-block; margin-right: 10px">弱关联</div>

          <div style="display: inline-block;background: #E6A23C; width: 10px;  height: 10px;  margin: 0 auto"/>
          <div style="display: inline-block;margin-right: 10px">半关联</div>

          <div style="display: inline-block;background: #67C23A;   width: 10px;  height: 10px;  margin: 0 auto"/>
          <div style="display: inline-block;margin-right: 10px">强关联</div>

          <div style="display: inline-block;background: #409EFF;width: 10px;height: 10px; margin: 0 auto"/>
          <div style="display: inline-block;margin-right: 10px">全关联</div>
        </el-form-item>

      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import course from '@/api/management/course'
import Sortable from 'sortablejs'
import axios from "axios";
import {getToken} from '@/utils/auth'

export default {
  data() {
    return {
      page: 1,
      limit: 10,
      total: 0,
      headers: {
        token: getToken(),
      },
      importDataDisabled: false,
      importDataBtnIcon: 'el-icon-upload2',
      importDataBtnText: '导入数据',
      chosenCourseIds: [],
      courseList: [],
      courseDialogFormVisible: false,
      nextCourseDialogFormVisible: false,
      allCoursesId: [],
      relationLevelList: [
        {
          relationLevel: 1,
          relationName: '弱关联'
        },
        {
          relationLevel: 2,
          relationName: '半关联'
        },
        {
          relationLevel: 3,
          relationName: '强关联'
        },
        {
          relationLevel: 4,
          relationName: '全关联'
        },
      ],
      nextCoursesIdAndName: {
        courseId: '',
        nextCourseId: '',
        relationLevel: ''
      },
      // 当前课程对应的后继课程信息
      nextCourseList: [{
        courseId: '',
        courseName: '',
        relationLevel: ''
      }],
      // 弹框中的当前课程信息
      currentCourse: {
        courseId: '',
        courseName: ''
      },
      // 编辑后继课程弹出框中的下拉框中所有的课程序号与名称
      canBeAddedNextCourseList: {
        courseId: '',
        courseName: ''
      },
      // 表格中的课程信息
      courseInfo: {
        courseId: '',
        courseName: '',
        propertiesKey: '',
        propertiesValue: ''
      },
      // 组合课程查询条件
      courseQueryObj: {
        courseId: '',
        courseName: '',
        nextCourseStr: '',
        propertiesKey: '',
        propertiesValue: '',
        createdByName: '',
        beginTime: '',
        updateTime: ''
      },
      colorObj: {
        '1': 'info',
        '2': 'warning',
        '3': 'success',
        '4': ''
      }
    }
  },
  created() {
    this.getCourseList()
  },
  mounted() {
    // this.rowDrop()
  },
  methods: {
    onError() {
      this.importDataBtnIcon = 'el-icon-upload2'
      this.importDataBtnText = '导入数据'
      this.importDataDisabled = false
    },
    onSuccess() {
      this.importDataBtnIcon = 'el-icon-upload2'
      this.importDataBtnText = '导入数据'
      this.importDataDisabled = false
      this.getCourseList()
    },
    beforeUpload() {
      this.importDataBtnIcon = 'el-icon-loading'
      this.importDataBtnText = '正在导入'
      this.importDataDisabled = true
    },
    // 导入Excel
    handleImport(param) {
      const formData = new FormData()
      formData.append('file', param.file)
      axios({
        headers: {
          'token': getToken(),
          'Content-type': 'multipart/form-data'
        },
        //这里也可以是 blob
        method: "post",
        url: 'http://localhost:8080/courses/importCourseData',
        responseType: "blob",
        data: formData
      }).then(res => {
        // this.$message({
        //   type: 'success',
        //   message: '添加成功!'
        // })
        this.onSuccess()
      }).catch(res => {
        this.$message({
          type: 'error',
          message: '添加失败!'
        })
        this.onError()
      })
    },
    // 获取选中数据
    handleSelectionChange(chosenCourses) {
      this.chosenCourseIds = []
      chosenCourses.forEach(item => {
        this.chosenCourseIds.push(item.courseId)
      })
      console.log("this.chosenCourseIds", this.chosenCourseIds)

    },
    // 导出Excel
    handleExport() {
      // 发送请求，导出选中数据
      axios({
        headers: {'token': getToken()},
        //这里也可以是 blob
        method: "post",
        url: 'http://localhost:8080/courses/exportCourseData',
        responseType: "blob",
        data: this.chosenCourseIds,
      }).then(res => {
        const link = document.createElement("a");
        let blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.setAttribute("download", decodeURI(Date.now() + '课程表.xlsx'));
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
    },
    //行拖拽
    // rowDrop() {
    //   const tbody = document.querySelector('.el-table__body-wrapper tbody')
    //   const _this = this
    //   Sortable.create(tbody, {
    //     animation: 180,
    //     delay: 0,
    //     onEnd({newIndex, oldIndex}) {
    //       const currRow = _this.courseList.splice(oldIndex, 1)[0]
    //       _this.courseList.splice(newIndex, 0, currRow)
    //     }
    //   })
    // },
    // 跳转到目录页面
    gotoCategory(courseId) {
      this.$router.push(`/categoryDetail/${courseId}`)
    },
    // 增加后继课程
    addNextCourse(currentCourseId, newNextCourse) {
      newNextCourse.nextCourseId = newNextCourse.courseId
      newNextCourse.courseId = currentCourseId
      course.addCourseRelation(newNextCourse)
        .then(response => {
          // 添加成功后，重新渲染后继课程标签列表
          course.getNextCourseList(currentCourseId)
            .then(response => {
              const {nextCourseList, relationLevelList} = response.data
              this.nextCourseList = nextCourseList
              if (this.nextCourseList) {
                this.nextCourseList.forEach((item, index) => {
                  item.relationLevel = relationLevelList[index]
                })
              }
              this.nextCoursesIdAndName = {}
            })
          // 重新渲染可添加的后继课程列表
          course.getCanBeAddedNextCourseList(currentCourseId)
            .then(response => {
              this.canBeAddedNextCourseList = response.data.canBeAddedNextCourseList
            })
          this.getCourseList()
        })
    },
    // 删除后继课程
    handleNextCourseTagClose(nextCourse) {
      // 官方操作：删除该个标签
      this.nextCourseList.splice(this.nextCourseList.indexOf(nextCourse), 1)
      // 执行删除操作
      course.deleteCourseRelation(this.currentCourse.courseId, nextCourse.courseId)
        .then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 重新渲染可添加的后继课程列表
          course.getCanBeAddedNextCourseList(this.currentCourse.courseId)
            .then(response => {
              this.canBeAddedNextCourseList = response.data.canBeAddedNextCourseList
            })
          // 重新查询所有数据,刷新表格内容
          this.getCourseList()
        })
    },
    // 修改后继课程信息
    openNextCourseDialogForm(currentCourse) {
      // 回显当前课程
      this.currentCourse.courseId = currentCourse.courseId
      this.currentCourse.courseName = currentCourse.courseName
      // 查询所有课程的序号和名称
      course.getCanBeAddedNextCourseList(currentCourse.courseId)
        .then(response => {
          this.canBeAddedNextCourseList = response.data.canBeAddedNextCourseList
        })
      // 渲染所有关联课程标签
      course.getNextCourseList(currentCourse.courseId)
        .then(response => {
          this.nextCourseList = response.data.nextCourseList
          let relationLevelList = response.data.relationLevelList
          if (this.nextCourseList != null) {
            for (let i = 0; i < this.nextCourseList.length; i++) {
              this.nextCourseList[i].relationLevel = relationLevelList[i]
            }
          }
        })
      this.nextCourseDialogFormVisible = true
    },
    // 增加课程信息
    addCourse() {
      this.courseDialogFormVisible = true
      this.courseInfo = {}
    },
    // 每次关闭弹窗，就清空回显的信息
    clearCourseInfo() {
      this.courseDialogFormVisible = false
      this.courseInfo = {}
    },
    // 新增或更新课程信息
    updateOrCourseInfo() {
      if (this.courseInfo.courseId === undefined) {
        // 课程信息无id信息，说明是新增
        course.addCourse(this.courseInfo)
          .then(response => {
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
            this.courseDialogFormVisible = false
            // 重新查询所有数据
            this.getCourseList()
          })
      } else {
        // 课程信息有id信息，说明是修改
        course.updateCourseInfo(this.courseInfo)
          .then(response => {
            this.$message({
              type: 'success',
              message: '更新成功!'
            })
            this.courseDialogFormVisible = false
            // 重新查询所有数据
            this.getCourseList()
          })
      }
    },
    // 打开修改课程信息弹出框
    openCourseDialogForm(course) {
      // 打开弹框
      this.courseDialogFormVisible = true
      // 回显信息
      this.courseInfo.courseId = course.courseId
      this.courseInfo.courseName = course.courseName
      this.courseInfo.propertiesKey = course.propertiesKey
      this.courseInfo.propertiesValue = course.propertiesValue
    },
    // 根据课程id删除课程信息
    deleteCourseById(courseId) {
      this.$confirm('此操作将删除改课程信息及下的目录、知识点、资源等信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //调用删除方法
        course.deleteCourse(courseId)
          .then(response => {
            //提示删除成功
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            //刷新列表
            this.getCourseList()
          })
      })
    },
    // 获取课程列表
    getCourseList(page = 1) {
      this.page = page
      course.getCoursesPage(this.page, this.limit, this.courseQueryObj)
        .then(response => {
          this.courseList = response.data.rows
          this.total = response.data.total
        })
    },
    // 重置搜索条件
    resetData() {
      //清空查询条件
      this.courseQueryObj = {}
      // 重新查询所有数据
      this.getCourseList()
    },
  }
}
</script>
<style>
.buttonClass {
  padding-bottom: 20px;
}

.noBorder {
  border: 0px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}


.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>


